package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.service.EBuyGoodsService;
import com.chhuang.ewcrm.service.EMaxNumberService;
import com.chhuang.ewcrm.service.EWarehouseService;
import com.chhuang.ewcrm.vo.ResultBean;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (EWarehouse)表控制层
 *
 * @author chhuang
 * @since 2020-11-10 12:38:51
 */
@RestController
@RequestMapping("/service/eWarehouse")
public class EWarehouseController {
    Logger logger = LoggerFactory.getLogger(EWarehouseController.class);
    /**
     * 服务对象
     */
    @Resource
    private EWarehouseService eWarehouseService;
    @Resource
    private EMaxNumberService eMaxNumberService;
    @Resource
    private EBuyGoodsService eBuyGoodsService;

    /**
     * 获取所有仓库
     *
     * @return 单条数据
     */
    @GetMapping("/getAll")
    public ResultBean<List<EWarehouse>> getAll() {
        ResultBean<List<EWarehouse>> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);
        resultBean.setData(this.eWarehouseService.query(null, "create_time"));
        return resultBean;
    }

    /**
     * 删除仓库
     * @param warehouseId
     * @return
     */
    @DeleteMapping("/removeOne/{warehouseId}")
    public ResultBean<?> removeOne(@PathVariable("warehouseId") String warehouseId){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);
        if(StringUtils.isNotEmpty(warehouseId)){
            //删除码单
            deleteMaxNumber(warehouseId);
            //删除仓库
            resultBean.setSuccess(this.eWarehouseService.deleteById(warehouseId));
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 根据id列表批量删除
     * @param warehouseIds
     * @return
     */
    @PutMapping("/removeList")
    public ResultBean<?> removeList(@RequestBody List<String> warehouseIds){
        ResultBean<?> resultBean = new ResultBean<>();
        if(warehouseIds!=null && !warehouseIds.isEmpty()){
            warehouseIds.forEach(this::deleteMaxNumber);
            resultBean.setSuccess(this.eWarehouseService.deleteByIds(warehouseIds)>0);
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 删除码单号
     * @param warehouseId
     */
    private void deleteMaxNumber(String warehouseId){
        EWarehouse eWarehouse = this.eWarehouseService.queryById(warehouseId);
        if(eWarehouse!=null){
            String ename = eWarehouse.getWarehouseEname();
            if(StringUtils.isNotEmpty(ename)) {
                //删除码单
                EMaxNumber eMaxNumber = new EMaxNumber();
                eMaxNumber.setWarehouseEname(ename);
                this.eMaxNumberService.deleteByEntity(eMaxNumber);
            }
        }
    }

    /**
     * 检验仓库的字母编号是否存在
     * @param ename
     * @param warehouseId
     * @return
     */
    @GetMapping("/checkEname")
    public ResultBean<?> checkEname(String ename, String warehouseId){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(ename)){
            EWarehouse eWarehouse = new EWarehouse();
            eWarehouse.setWarehouseEname(ename);
            List<EWarehouse> eWarehouses = eWarehouseService.query(eWarehouse);
            if(eWarehouses==null || eWarehouses.isEmpty() || eWarehouses.get(0).getWarehouseId().equals(warehouseId)){//ename不存在
                resultBean.setSuccess(true);
            }else {
                resultBean.setMessage("此仓库的字母编号已存在");
            }
        }else {
            resultBean.setMessage("字母编号参数不能为空");
        }

        return resultBean;
    }

    /**
     * 修改仓库信息
     * @param eWarehouse
     * @return
     * @throws IOException
     */
    @PutMapping("/editOne")
    public ResultBean<EWarehouse> editOne(@RequestBody EWarehouse eWarehouse){
        ResultBean<EWarehouse> resultBean = new ResultBean<EWarehouse>();
        resultBean.setSuccess(false);
        if(eWarehouse!=null && StringUtils.isNotEmpty(eWarehouse.getWarehouseName()) &&
                StringUtils.isNotEmpty(eWarehouse.getWarehouseEname()) &&
                checkEname(eWarehouse.getWarehouseEname(), eWarehouse.getWarehouseId()).isSuccess()) {
            Date now = new Date();
            if (StringUtils.isEmpty(eWarehouse.getWarehouseId())) { //添加
                eWarehouse.setCreateTime(now);
                eWarehouse.setModifyTime(now);
                eWarehouse = this.eWarehouseService.insert(eWarehouse);
                resultBean.setData(eWarehouse);
                resultBean.setSuccess(resultBean.getData()!=null);
                //添加 码单号
                EMaxNumber eMaxNumber = null;
                List<EMaxNumber> eMaxNumbers = new LinkedList<>();
                for (String wtype : EwcrmConstants.WEIGH_TYPES){
                    eMaxNumber = new EMaxNumber();
                    eMaxNumber.setWarehouseEname(eWarehouse.getWarehouseEname());
                    eMaxNumber.setNumber(1l);
                    eMaxNumber.setWeighTypeEname(wtype);
                    eMaxNumber.setCreateTime(now);
                    eMaxNumber.setModifyTime(now);
                    eMaxNumbers.add(eMaxNumber);
                }
                eMaxNumberService.insertBatch(eMaxNumbers);
            } else{ //修改
                EWarehouse warehouse = eWarehouseService.queryById(eWarehouse.getWarehouseId());
                if (warehouse != null) {
                    //当仓库的字母编码修改时 要同时 修改 码单表
                    if(!warehouse.getWarehouseEname().equalsIgnoreCase(eWarehouse.getWarehouseEname())) {
                        EMaxNumber eMaxNumber = new EMaxNumber();
                        eMaxNumber.setWarehouseEname(warehouse.getWarehouseEname());
                        List<EMaxNumber> maxNumbers = this.eMaxNumberService.query(eMaxNumber);
                        if (maxNumbers != null && !maxNumbers.isEmpty()) {
                            for (int i = 0; i < maxNumbers.size(); i++) {
                                eMaxNumber = maxNumbers.get(i);
                                eMaxNumber.setWarehouseEname(eWarehouse.getWarehouseEname());
                                eMaxNumber.setModifyTime(now);
                                maxNumbers.set(i, eMaxNumber);
                            }
                        }
                        eMaxNumberService.updateBatch(maxNumbers);
                    }
                    //修改仓库名称 要同时 修改 原料和产品表
                    if(!warehouse.getWarehouseName().equals(eWarehouse.getWarehouseName())) {
                        EBuyGoods eBuyGoods = new EBuyGoods();
                        eBuyGoods.setWarehouseId(warehouse.getWarehouseId());
                        List<EBuyGoods> eBuyGoodsList = eBuyGoodsService.query(eBuyGoods);
                        if(eBuyGoodsList!=null && !eBuyGoodsList.isEmpty()){
                            for(int i=0;i<eBuyGoodsList.size();i++){
                                eBuyGoods = eBuyGoodsList.get(i);
                                eBuyGoods.setWarehouseName(eWarehouse.getWarehouseName());
                                eBuyGoods.setModifyTime(now);
                                eBuyGoodsList.set(i, eBuyGoods);
                            }
                            eBuyGoodsService.updateBatch(eBuyGoodsList);
                        }
                    }
                    //修改仓库信息
                    warehouse.setWarehouseName(eWarehouse.getWarehouseName());
                    warehouse.setWarehouseEname(eWarehouse.getWarehouseEname());
                    warehouse.setModifyTime(now);
                    eWarehouse = this.eWarehouseService.update(warehouse);
                    resultBean.setData(eWarehouse);
                    resultBean.setSuccess(resultBean.getData()!=null);
                } else
                    resultBean.setMessage("没有找到仓库");
            }
        } else
            resultBean.setMessage("参数不能为空，或者仓库字母编号已存在");
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param warehouseId 主键
     * @return 单条数据
     */
    @GetMapping("/getOne")
    public ResultBean<EWarehouse> getOne(String warehouseId) {
        ResultBean<EWarehouse> resultBean = new ResultBean<EWarehouse>();
        resultBean.setSuccess(false);
        if(StringUtils.isNotEmpty(warehouseId)){
            resultBean.setSuccess(true);
            resultBean.setData(this.eWarehouseService.queryById(warehouseId));
        }else{
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 表格查询
     * @param queryBean
     * @return
     */
    @PostMapping("/queryPage")
    public ResultBean<PageInfo<EWarehouse>> query(@RequestBody QueryBean<EWarehouse> queryBean){
        logger.debug(queryBean.toString());
        ResultBean<PageInfo<EWarehouse>> resultBean = new ResultBean<>();

        PageInfo<EWarehouse> pageInfo = null;
        List<EWarehouse> warehouses = null;
        if(queryBean!=null) {
            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = eWarehouseService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = eWarehouseService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
            resultBean.setSuccess(true);
            resultBean.setCode(queryBean.getDraw());
        }else {
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

}